<?php
namespace wap\models;

use Yii;
use yii\base\Model;
use yii\helpers\Json;

/**
 * Signin form
 *
 * @property $product_id
 * @property $veneer
 * @property $outside_handle
 * @property $inside_handle
 * @property $lockset
 * @property $size
 * @property $quantity
 */
class CartForm extends Model
{
    public $product_id;
    public $veneer;
    public $outside_handle;
    public $inside_handle;
    public $lockset;
    public $size;
    public $quantity;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['product_id', 'size', 'quantity'], 'required'],
            [['veneer', 'outside_handle', 'inside_handle', 'lockset', 'size', 'quantity'], 'trim'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'product_id' => '产品 ID',
            'veneer' => '内饰面',
            'outside_handle' => '外把手',
            'inside_handle' => '内把手',
            'lockset' => '锁具',
            'size' => '尺寸',
            'quantity' => '数量',
        ];
    }

    /**
     * @return \home\models\Cart|bool|null
     */
    public function save()
    {
        if(!$this->validate()){
            return false;
        }

        $data = Json::encode($this->getAttributes(['veneer', 'outside_handle', 'inside_handle', 'lockset', 'size']));
        $model = Cart::find()->where(['user_id' => Yii::$app->user->id, 'product_id' => $this->product_id, 'data' => $data])->one();
        if(!$model){
            $model = new Cart();
            $model->id = $model::genId();
            $model->user_id = Yii::$app->user->id;
            $model->product_id = $this->product_id;
            $model->data = $data;
            $model->quantity = 0;
        }
        $model->quantity += $this->quantity;
        if($model->save()){
            return true;
        }

        return false;
    }
}
